package com.gitlab.lucky.eleme.service;

import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gitlab.lucky.common.dao.model.ElemCookie;
import com.gitlab.lucky.common.dao.model.LuckyRecord;
import com.gitlab.lucky.common.enums.CodeEnum;
import com.gitlab.lucky.common.enums.Constant;
import com.gitlab.lucky.common.redis.RedisService;
import com.gitlab.lucky.eleme.model.LuckyResult;
import com.gitlab.lucky.eleme.model.PromotionRecords;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Date;

/**
 * @program: lucky
 * @author: Mr.Han
 * @create: 2018-10-27 11:45
 **/
@Service
public class ElemHandleService {
    public static final Logger LOGGER = LoggerFactory.getLogger(ElemHandleService.class);
    @Autowired
    private RedisService redisService;
    @Autowired
    private LuckyRecordService luckyRecordService;
    @Autowired
    private ElemCookieService elemCookieService;

    /**
     * 抢红包
     *
     * @param sn
     * @return
     */
    public CodeEnum handle(String openId, String sn, Integer lucky_number, Integer platform) {
        //redis队列取小号
        Object elem_ck = redisService.pop(Constant.ELEM_CK_KEY);
        //没有小号了
        if (elem_ck == null) {
            return CodeEnum.NOT_COOKIE;
        }
        //转对象
        ElemCookie elem = (ElemCookie) elem_ck;
        //抢红包请求
        LuckyResult result = requestLuckyUrl(sn, elem.getSid(), elem.getOpenid(), elem.getElemeKey());
        //判断elem返回值
        CodeEnum codeEnum = ifResult(result, elem);
        //ck请求失败,或者请求频繁,需要递归
        if (codeEnum.getCode() == CodeEnum.FOREACH.getCode()) {
            return handle(openId, sn, lucky_number, platform);
        }
        //红包被抢完了,或者已过期
        if (codeEnum.getCode() != CodeEnum.SUCCESS.getCode()) {
            return codeEnum;
        }
        //已抢红包集合
        ArrayList<PromotionRecords> promotion_records = result.getPromotion_records();
        //已抢红包数量
        int size = promotion_records.size();
        LOGGER.info("ID:{},RET_CODE:{},最大为:{}个,以抢第{}个,金额:{}", elem.getId(), result.getRet_code(), lucky_number, size, promotion_records.get(size - 1).getAmount());
        //已抢红包数量大于等于大红包
        if (size >= lucky_number) {
            return CodeEnum.NOT_LUCKY;
        }
        //已抢红包数量+1等于大红包
        if (size + 1 == lucky_number) {
            //添加抢红包成功记录
            createLuckyRecord(openId, sn, platform, elem, lucky_number);
            return CodeEnum.SUCCESS;
        }

        return handle(openId, sn, lucky_number, platform);
    }

    /**
     * 添加抢红包成功记录
     *
     * @param openId
     * @param sn
     * @param platform
     */
    public void createLuckyRecord(String openId, String sn, Integer platform, ElemCookie elem, Integer luckyNumber) {
        LuckyRecord luckyRecord = new LuckyRecord();
        luckyRecord.setOpenid(openId);
        luckyRecord.setSn(sn);
        luckyRecord.setIsSuccess(Constant.TRUE);
        luckyRecord.setCreateTime(new Date());
        luckyRecord.setPlatform(platform);
        luckyRecord.setCkOpenid(elem.getOpenid());
        luckyRecord.setCkElemkey(elem.getElemeKey());
        luckyRecord.setCkSid(elem.getSid());
        luckyRecord.setLuckyNumber(luckyNumber);
        luckyRecordService.insert(luckyRecord);
    }

    /**
     * 判断饿了么返回值
     *
     * @param result
     * @param elem
     * @return
     */
    public CodeEnum ifResult(LuckyResult result, ElemCookie elem) {
        if (result.getRet_code() != 4) {
            switch (result.getRet_code()) {
                case 0:
                    if (result.getMessage().contains("频繁") ||
                            result.getMessage().contains("试") ||
                            result.getMessage().contains("异常") ||
                            result.getMessage().contains("问题") ||
                            result.getMessage().contains("正在疯抢")) {
                        redisService.push(Constant.ELEM_CK_KEY, elem);
                    } else if (result.getMessage().equals("未登录")) {
                        elem.setIsDelete(Constant.TRUE);
                        elem.setModifyTime(new Date());
                        elemCookieService.updateByPrimaryKeySelective(elem);
                    }
                    LOGGER.info("ERROR_ELEM_ID:{}", elem.getId());
                    LOGGER.info("REQUEST_RESULT:{}", JSON.toJSONString(result));
                    //ck有问题
                    return CodeEnum.FOREACH;
                case 1:
                    //红包被抢完了
                    redisService.push(Constant.ELEM_CK_KEY, elem);
                    return CodeEnum.NOT_LUCKY;
                case 2:
                    // 这个号抢过这个红包
                    LOGGER.info("以抢过,ID:{}", elem.getId());
                    redisService.push(Constant.ELEM_CK_KEY, elem);
                    return CodeEnum.FOREACH;
                case 5:
                    // 没次数了，有可能是手机号没次数了，也有可能是 cookie 没次了
                    LOGGER.info("次数不足,ID:{}", elem.getId());
                    return CodeEnum.FOREACH;
                case 12:
                    // 红包已过期
                    redisService.push(Constant.ELEM_CK_KEY, elem);
                    return CodeEnum.LUCKY_TIMEOUT;
            }
            LOGGER.info("ERROR_CK_ID:{},RET_CODE,RET_MSG", elem.getId(), result.getRet_code(), result.getMessage());
            redisService.push(Constant.ELEM_CK_KEY, elem);
            LOGGER.info(JSONObject.toJSONString(result));
            return CodeEnum.SERVER_INTERNAL_ERROR;
        }
        return CodeEnum.SUCCESS;
    }

    /**
     * 请求elem抢红包接口
     *
     * @return
     */
    public LuckyResult requestLuckyUrl(String sn, String sid, String openId, String elemKey) {
        try {
            Thread.sleep(70000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String url = String.format(Constant.HONGBAO_URL, openId);
        String result = HttpUtil.createRequest(Method.POST, url)
                .cookie("SID=" + sid)
                .form("sign", elemKey)
                .form("group_sn", sn)
                .timeout(3000)
                .execute()
                .body();;
        LuckyResult luckyResult = JSONObject.parseObject(result, LuckyResult.class);
        return luckyResult;
    }

}
